import mysql from 'mysql2/promise';
import { drizzle } from 'drizzle-orm/mysql2';
import { DB_CONFIG } from '../config/index.js';

// 创建MySQL连接池
const pool = mysql.createPool({
  host: DB_CONFIG.host,
  port: DB_CONFIG.port,
  user: DB_CONFIG.user,
  password: DB_CONFIG.password,
  database: DB_CONFIG.database,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  acquireTimeout: 60000,
  timeout: 60000,
});

// 创建Drizzle数据库实例
export const db = drizzle(pool);

// 测试数据库连接
export async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('✅ 数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    console.error('请检查以下配置:');
    console.error('- MySQL服务是否启动');
    console.error('- 数据库配置是否正确');
    console.error('- 数据库是否存在');
    return false;
  }
}
